package com.glory.good_dark.utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;

import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_TabIndexGridEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hx
 * @date 2019/11/15
 * @desc
 */
public class MyUtils {

    public interface  EditTextActionListener{
        void onKeyDown(String s);
    }

    public static List<FreeUI_TabIndexGridEntity> setPicToDrawable(Context context, List<FreeUI_TabIndexGridEntity> entity) {
        for (FreeUI_TabIndexGridEntity og : entity) {
            if (og.getPicName().length() != 0) {
                Drawable drawable = context.getResources()
                        .getDrawable(context.getResources()
                                .getIdentifier(og.getPicName(), "drawable", context.getPackageName()));
                og.setDrawable(drawable);
            }
        }
        return entity;
    }

    public static void editActionListener(EditText editText, EditTextActionListener listener){
        editText.setOnEditorActionListener((textView, actionId, keyEvent) -> {
            //当actionId == XX_SEND 或者 XX_DONE时都触发
            //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
            if (actionId == EditorInfo.IME_ACTION_SEND
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || (keyEvent != null && KeyEvent.KEYCODE_ENTER == keyEvent.getKeyCode() && KeyEvent.ACTION_DOWN == keyEvent.getAction())) {
                //处理事件
                listener.onKeyDown(editText.getText().toString().trim());
            }
            return false;
        });
    }

    public static void setEditTextListener(EditText editText, final Context context, final FreeUI_TextCallback callback) {
        editText.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (s.length() > 0) {
                        callback.onSuccess(s.toString());
                    } else {
                        FreeApi_ToastUtils.showFreeToast("扫描信息有误", context, false, 1);
                    }
                }

            }

            public void afterTextChanged(Editable s) {
            }
        });
    }
}
